package com.weikuang.fareast.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.adapter.WashingDemandAdapter;
import com.weikuang.fareast.bean.OfficeBean;
import com.weikuang.fareast.bean.SimpleBean;
import com.weikuang.fareast.bean.UsualGoodsBean;
import com.weikuang.fareast.bean.WashingDemandBean;
import com.weikuang.fareast.http.MainHttp;
import com.weikuang.fareast.utils.UserHelper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

//洗涤中心报废

public class HotelScrapActivity extends BaseActivity {

    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_offic)
    TextView tvOffic;
    @BindView(R.id.drop_offic)
    FrameLayout dropOffic;
    @BindView(R.id.item_offic)
    CommonItemView itemOffic;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_not)
    TextView tvNot;
    @BindView(R.id.drop_not)
    FrameLayout dropNot;
    @BindView(R.id.item_not)
    CommonItemView itemNot;
    @BindView(R.id.ed_not)
    EditText edNot;

    private CommonPopupList  mOfficPopup,mNotPopup;
    private List<OfficeBean.DataBean> mOfficList;
    private List<UsualGoodsBean.DataBean> mNotList;
    String offic_id = "",notNew_id;;
    int not_id = -1;
    List<WashingDemandBean> datasList = new ArrayList<>();
    WashingDemandAdapter mWashingDemandAdapter;

    private String mhotel_name = "";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_washscrap_must;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_washscrap_must);
        ButterKnife.bind(this);
        mhotel_name = UserHelper.get().gethotel()+"配送中心布草报废单";
        mTitleBar.setTitle(mhotel_name);
        initView();
        InitRecyclerView();
        getOffice();
    }
    private void initView() {
        mOfficPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropOffic)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvOffic.setText(item);
                        if (mOfficList != null) {
                            offic_id = mOfficList.get(position).id;
                            usualGoods(offic_id);
                            selectGoods(offic_id);
                        }

                    }
                })
                .build();
        mNotPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropNot)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvNot.setText(item);
                        if (mNotList != null) {
                            not_id = position;
                        }
                    }
                })
                .build();
    }

    private void InitRecyclerView() {
        mWashingDemandAdapter = new WashingDemandAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mWashingDemandAdapter);


        mWashingDemandAdapter.setOnItemClickListener(new WashingDemandAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, WashingDemandBean data, int position) {
                datasList.remove(position);
                mWashingDemandAdapter.setNewData(datasList);
            }
        });
    }

    @OnClick({R.id.drop_offic, R.id.drop_not, R.id.btn_add, R.id.btn_delete, R.id.btn_read})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_offic:
                mOfficPopup.showAsDropDown(view);
                break;
            case R.id.drop_not:
               // mNotPopup.showAsDropDown(view);
                if (mUsualGoodsBean != null && mUsualGoodsBean.data.size() > 0) {
                    Intent mIntent = new Intent(HotelScrapActivity.this, NotActivity.class);
                    mIntent.putExtra("data", mUsualGoodsBean);
                    startActivityForResult(mIntent, 2002);
                }else {
                    ToastUtil.show(this, "没有可选数据");
                }
                break;
            case R.id.btn_add:
                if (mNotList != null && mNotList.size() > 0) {
//                    if (!isAdd(mNotList.get(not_id).id)) {
//                        addData();
//                    }
                    if (!isAdd(notNew_id)) {
                        addData();
                    }
                }else {
                    ToastUtil.show(this,"没有可选数据");
                }
                break;
            case R.id.btn_delete:
                deleteData();
                break;
            case R.id.btn_read:
                killCommit();
                break;
        }
    }
    private boolean isAdd(String id){
        Iterator<WashingDemandBean> it = datasList.iterator();
        while (it.hasNext()) {
            WashingDemandBean str = it.next();
            if (str.id .equals(id)) {
                ToastUtil.show(this,"已经存在");
                return true;
            }
        }
        return false;
    }
    private void addData(){

        if (mSelect != null) {
            if (!TextUtils.isEmpty(edNot.getText().toString())&&Integer.parseInt(edNot.getText().toString()) > 0) {
                WashingDemandBean statisticsBean = new WashingDemandBean(UserHelper.get().gethotel(), tvOffic.getText().toString(), mSelect.title,
                        Integer.parseInt(edNot.getText().toString()), mSelect.id);
                //StatisticsBean statisticsBean = new StatisticsBean(mSelect.title, "0", Integer.parseInt(edNot.getText().toString()), 0, 0, mSelect.id);
                datasList.add(statisticsBean);
                mWashingDemandAdapter.setNewData(datasList);
                ToastUtil.show(this, "添加成功");
                tvNot.setText("品名");
                notNew_id = "";
                edNot.setText("0");
                mSelect = null;
            } else {
                ToastUtil.show(this, "数量要大于0");
            }
        }else {
            ToastUtil.show(this, "请先选择可选品名");
        }
    }

    private void deleteData(){
        Iterator<WashingDemandBean> it = datasList.iterator();
        while (it.hasNext()) {
            WashingDemandBean str = it.next();
            if (str.num == 0) {
                it.remove();
            }
        }
        mWashingDemandAdapter.setNewData(datasList);
    }
    private void getOffice() {
        MainHttp.get().getOffice("","")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<OfficeBean>() {
                    @Override
                    public void onSuccess(OfficeBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mOfficList = officeBean.data;
                        for (OfficeBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mOfficPopup.setData(datas);
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }

    private void usualGoods(String offic_id) {
        datasList.clear();
        mWashingDemandAdapter.setNewData(datasList);
        MainHttp.get().usualGoods(offic_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<UsualGoodsBean>() {
                    @Override
                    public void onSuccess(UsualGoodsBean officeBean) {

                        for (UsualGoodsBean.DataBean bean : officeBean.data) {
                            WashingDemandBean statisticsBean = new WashingDemandBean(UserHelper.get().gethotel(),tvOffic.getText().toString(), bean.spec, 0,bean.id);
                            datasList.add(statisticsBean);
                        }
                        mWashingDemandAdapter.setNewData(datasList);
                        if (officeBean.data != null && officeBean.data.size() > 0){
                            ToastUtil.show(getActivity(),officeBean.msg);
                        }else {
                            ToastUtil.show(getActivity(),"数据为空");
                        }
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }
    private UsualGoodsBean mUsualGoodsBean;
    private void selectGoods(String offic_id) {
        MainHttp.get().selectGoods(offic_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<UsualGoodsBean>() {
                    @Override
                    public void onSuccess(UsualGoodsBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mNotList = officeBean.data;
                        for (UsualGoodsBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mNotPopup.setData(datas);
                        mUsualGoodsBean= officeBean;
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }

    private void killCommit(){
        String goods_id = "",  nums = "";
        clearNums();
        for (int i = 0; i < datasList.size(); i++) {
            goods_id = goods_id + datasList.get(i).id + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            goods_id = goods_id.substring(0, goods_id.length() - 1);
        } else {
            goods_id = "";
        }

        for (int i = 0; i < datasList.size(); i++) {
            nums = nums + datasList.get(i).num + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            nums = nums.substring(0, nums.length() - 1);
        } else {
            nums = "";
        }
        showWaitingDialog("请等待",true);
        MainHttp.get().killCommit(offic_id,goods_id,nums)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean bean) {
                        ToastUtil.show(HotelScrapActivity.this,bean.msg);
                        dismissWaitingDialog();
                        datasList.clear();
                        mWashingDemandAdapter.setNewData(datasList);
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                        dismissWaitingDialog();
                    }
                });
    }

    /**
     * 是否清空为0数据
     * @return
     */
    private void clearNums(){
        Iterator<WashingDemandBean> ite = datasList.iterator();
        while(ite.hasNext()){
            WashingDemandBean str = (WashingDemandBean)ite.next();
            if(str.num == 0){
                ite.remove();
            }
        }
    }

    UsualGoodsBean.DataBean mSelect;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 5 && data != null) {
            mSelect = (UsualGoodsBean.DataBean) data.getSerializableExtra("data");
            if (mSelect != null) {
                tvNot.setText(mSelect.title);
                notNew_id = mSelect.id;
            }
        }
    }
}
